from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from django.contrib import auth


def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    else:
        username = request.POST.get("username")
        password = request.POST.get("password")
        # # 这里auth模块拿到用户名和密码后，会去auth_user表中查找数据，如果存在返回用户对象，不存在返回None
        user = auth.authenticate(username=username, password=password)
        if user:
            # auth.login方法执行会做的两件事：
            # 完成session的事情，将用户数据存入数据库，生成随机sessionid存在cookie中发送给客户端。
            # request.user = user_obj，将验证后的用户对象存在request请求对象中的user中
            # 只要使用login(request, user_obj)
            # 之后，request.user就能拿到当前登录的用户对象。
            auth.login(request, user)
            return render(request, "admin/welcome.html")
        else:
            return render(request, "login.html",{"msg":"用户名或密码错误！"})

def logout(request):
    request.session.flush()
    return redirect("/")

def toreg(request):
    return render(request, "reg.html")

def reg(request):
    msg="Sorry，用户名已被占用，注册失败。"
    username = request.POST.get("username")
    password = request.POST.get("password")
    if User.objects.filter(username=username).exists():
        return render(request, "reg.html", {"msg":msg})
    User.objects.create_user(username=username, password=password)
    return render(request, "reg.html", {"msg": "恭喜你，注册成功，请登录！"})

@login_required
def welcome(request):
    return render(request,'admin/welcome.html')

